package com.cygsunri.rbac.util;

import com.alibaba.fastjson.JSONObject;
import com.cygsunri.rbac.entity.Menu;

import java.util.ArrayList;
import java.util.List;

public class MenuHelper {

    /**
     * 使用递归方法建菜单
     * @param treeNodes
     * @return
     */
    public static List<Menu> bulid(List<Menu> treeNodes) {
        List<Menu> trees = new ArrayList<>();
        for (Menu treeNode : treeNodes) {
            if ("0".equals(treeNode.getParentId())) {
                //treeNode.setLevel(1);
                trees.add(findChildren(treeNode,treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @return
     */
    public static Menu findChildren(Menu treeNode, List<Menu> treeNodes) {
        treeNode.setRoutes(new ArrayList<Menu>());

        for (Menu it : treeNodes) {
            if(treeNode.getId().equals(it.getParentId())) {
                //int level = treeNode.getLevel() + 1;
                //it.setLevel(level);
                if (treeNode.getRoutes() == null) {
                    treeNode.setRoutes(new ArrayList<>());
                }
                treeNode.getRoutes().add(findChildren(it,treeNodes));
            }
        }
        return treeNode;
    }


    public static List<JSONObject> bulidJson(List<Menu> treeNodes) {
        List<JSONObject> meuns = new ArrayList<>();

        for (Menu topNode : treeNodes) {
            meuns.add(addMenuNode(topNode));
        }
        return meuns;
    }

    private static JSONObject addMenuNode(Menu parentNode) {
        JSONObject meunNode = new JSONObject();

        meunNode = addProperties(meunNode, parentNode);

        List<JSONObject> routes = new ArrayList<>();

        List<Menu> routesList = parentNode.getRoutes();

        for(Menu childNode :routesList) {
            routes.add(addMenuNode(childNode));
        }
        if (!routes.isEmpty()) {
            meunNode.put("routes", routes);
        }

        return meunNode;
    }


    private static JSONObject addProperties(JSONObject obj, Menu node) {

        if (node.getPath()!=null) {
            obj.put("path", node.getPath());
        }

        if (node.getComponent()!=null) {
            obj.put("component", node.getComponent());
        }

        if (node.getRedirect()!=null) {
            obj.put("redirect", node.getRedirect());
        }

        if (node.getName()!=null) {
            obj.put("name", node.getName());
        }

        if (node.getIcon()!=null) {
            obj.put("icon", node.getIcon());
        }

        return obj;
    }

}
